package com.alcatel.axs.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.jboss.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import com.alcatel.axs.dao.impl.ServerDAOImpl;
import com.alcatel.axs.model.Server;
import com.alcatel.axs.service.ClusterManagerService;
import com.alcatel.axs.util.ClusterManagerUtils;

@Component
@Service
public class ClusterManagerServiceImpl implements ClusterManagerService {

    private static final Logger m_logger = Logger.getLogger(ClusterManagerServiceImpl.class);
    
    @Autowired
    private ServerDAOImpl m_serverDao;
    
    public ClusterManagerServiceImpl() {
    }
    @Autowired
    public ClusterManagerServiceImpl(ServerDAOImpl serverDAOImpl) {
        m_serverDao=serverDAOImpl;
    }

    @Override
    public List<Server> getServer() {
        return m_serverDao.getServer();
    }

    @Override
    public List<String> getStatus(String ip) {
        List<String> result = new ArrayList<String>();
        try {
            result=ClusterManagerUtils.getClusterStatus(ip, "amssys", "amssys");
        } catch (Exception e) {
            m_logger.error(e.getMessage(),e);
        }
        if(!result.isEmpty()){
            Server server = new Server();
            server.setIp(ip);
            if (!m_serverDao.findByIp(server)){
                m_serverDao.insert(server);
            }
            String status = "";
            status = ClusterManagerUtils.getServerStatus(result, ip);
            server.setStatus(status);
            m_serverDao.updateStatusByIp(server);
            
        }
        return result;
    }
    
    @Override
    public List<String> startServer(String ip) {
        List<String> result = new ArrayList<String>();
        try {
            result=ClusterManagerUtils.excuteCommand(ip, "amssys", "amssys","start");
        } catch (Exception e) {
            m_logger.error(e.getMessage(),e);
        }
        return result;
    }
    
    @Override
    public List<String> stopServer(String ip) {
        List<String> result = new ArrayList<String>();
        try {
            result=ClusterManagerUtils.excuteCommand(ip, "amssys", "amssys","stop");
        } catch (Exception e) {
            m_logger.error(e.getMessage(),e);
        }
        return result;
    }

}
